package com.zwj.interview.哈希表;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Zwj
 * @Date: 2022/9/19 17:57
 *
 *
 * 找出两个单词在一个字符串数组中的最小距离
 */
public class WordDistance {

    //用来记录字符串数组中每个单词的索引
    Map<String, List<Integer>> map=new HashMap<>();

    //初始化map
    public WordDistance(String[] words){
          for(int i=0;i<words.length;i++){
              if(map.containsKey(words[i])){
                  map.get(words[i]).add(i);
              }else{
                  List<Integer> list=new ArrayList<>();
                  list.add(i);
                  map.put(words[i],list);
              }
          }
    }


    public int shortestDistance(String word1,String word2){
        List<Integer> list1=map.get(word1);
        List<Integer> list2=map.get(word2);
        int i=0;
        int j=0;
        int result=Integer.MAX_VALUE;
        //接下来就在两个集合中找出最短距离
        while(i<list1.size() && j<list2.size()){
            //小的数往前欧
            if(list1.get(i)<list2.get(j)){
                result=Math.min(result, list2.get(j)-list1.get(i));
                i++;
            }else{
                result=Math.min(result,list1.get(i)-list2.get(j));
                j++;
            }

        }
        return result;
    }



}